<template>
<view>
  <u-sticky :h5-nav-height="0" bg-color="white">
    <view class="sticky-bg">
      <u-navbar title-bold
                :is-fixed="false"
                :titleSize="34"
                :is-back="false"
                :border-bottom="false"
                :background="{background:'white'}"
                title-color="#2F3033"
      >
        <template v-slot:left>
          <view class="back-wrap"  @click="back()">
            <image src="/yixu/static/images/dynamic_code/back.png"></image>
            <text>{{formData.id ? '编辑二维码':'新建二维码'}}</text>
          </view>
        </template>
      </u-navbar>
    </view>
  </u-sticky>
  <u-modal v-model="modalOption.show" :title="modalOption.title" :show-confirm-button="false">
    <view style="padding: 30rpx">
      <view class="input-wrap" v-if="modalOption.type === 'input'">
        <input class="modal-input" placeholder="请输入" v-model="modalOption.value" type="text"/>
        <view v-if="modalOption.extra.inputType==='number'">年</view>
      </view>
      <view v-if="modalOption.type === 'time'">
        <view class="input-wrap" style="display: flex;justify-content: space-between;">
          <input class="modal-input" placeholder="请输入" v-model="modalOption.value" type="number"/>
          <view>分钟</view>
        </view>
        <view style="color: #999999;font-size: 24rpx;padding-top: 20rpx;">0 为 长期有效</view>
      </view>
      <view v-if="modalOption.type === 'limit'">
        <view class="input-wrap" style="display: flex;justify-content: space-between;">
          <input class="modal-input" placeholder="请输入" v-model="modalOption.value" type="number"/>
          <view>次</view>
        </view>
        <view style="color: #999999;font-size: 24rpx;padding-top: 20rpx;">0 为 不限次数</view>
      </view>
      <view v-if="modalOption.type === 'password'">
        <view class="input-wrap" style="display: flex;justify-content: space-between;">
          <input class="modal-input" placeholder="请输入密码" v-model="modalOption.value" type="text"/>
        </view>
      </view>

      <view v-if="modalOption.type === 'product'">
        <select_tag v-for="item in productList" :key="item.id" :active="!formData.goods_ids.includes(item.id)"
                    :text="item.name" @select="onSelectFormTag(item.id,'goods_ids')"/>

      </view>

      <u-button :custom-style="{color:'white',background:'#3F70FF',marginTop:'30rpx'}" @click="onModalConfirm">
        保存
      </u-button>
    </view>
  </u-modal>

  <view style="padding-right: 30rpx;background: #F2F3F5;margin:0 30rpx;border-radius: 10rpx;"
        @click="openModal('goods_ids','选择产品','product')">
    <view class="readonly row">
      <u-search placeholder="请选择产品"
                :value=" formData.goods_ids.length > 0 ? '已选' + formData.goods_ids.length +'个产品' :'' "
                shape="square" bg-color="#F2F3F5">
      </u-search>
      <u-icon name="arrow-down" color="#C9CDD4"></u-icon>
    </view>
  </view>
  <view class="form-wrap mt30">
    <view class="title-area">二维码显示设置</view>
    <view class="form-item">
      <view class="form-item-inner">
        <view class="label-wrap">
          <text class="required">*</text>
          <text>产品名称</text>
        </view>
        <view class="value-wrap">
          <input class="input" v-model="formData.name" placeholder-class="input-pl" placeholder="请输入名称"/>
        </view>
      </view>
    </view>
    <view class="form-item">
      <view class="form-item-inner">
        <view class="label-wrap">
          <text>备注</text>
        </view>
        <view class="value-wrap">
          <input class="input" v-model="formData.notes" placeholder-class="input-pl" placeholder="请输入备注"/>
        </view>
      </view>
    </view>
  </view>
  <view class="form-wrap">
    <view class="title-area">客户经理信息</view>
    <view class="form-item">
      <view class="form-item-inner">
        <view class="label-wrap">
          <text class="required">*</text>
          <text>姓名</text>
        </view>
        <view class="value-wrap">
          <input class="input" v-model="formData.manager_name" placeholder-class="input-pl" placeholder="请输入姓名"/>
        </view>
      </view>
    </view>
    <view class="form-item">
      <view class="form-item-inner">
        <view class="label-wrap">
          <text>手机号</text>
        </view>
        <view class="value-wrap">
          <input class="input" v-model="formData.manager_phone" placeholder-class="input-pl"
                 placeholder="请输入手机号"/>
        </view>
      </view>
    </view>
    <view class="form-item">
      <view class="form-item-inner">
        <view class="label-wrap">
          <text>显示LOGO</text>
        </view>
        <view class="value-wrap flex1 u-text-right">
          <u-switch v-model="formData.is_display_logo"></u-switch>
        </view>
      </view>
    </view>
    <view class="form-item">
      <view class="form-item-inner">
        <view class="label-wrap">
          <text>显示到期时间</text>
        </view>
        <view class="value-wrap flex1  u-text-right">
          <u-switch v-model="formData.is_display_expiration"></u-switch>
        </view>
      </view>
    </view>
  </view>

  <view class="form-wrap">
    <view class="title-area">权限设置</view>
    <view class="form-item" style="padding-bottom: 0;">
      <view class="form-item-inner">
        <view class="label-wrap">
          <text>二维码有效期</text>
        </view>
        <view class="value-wrap flex1 u-text-right">
          <view class="main-color" @click="openModal('end_time','设置二维码有效期','time')">
            <text class="mr5">{{ formData.end_time == 0 ? '长期有效' : formData.end_time + '分钟' }}</text>
            <u-icon name="arrow-down"></u-icon>
          </view>
        </view>
      </view>
      <view>
        <view class="desc-text">二维码到期后不会被删除，但扫码后会显示该</view>
        <view class="form-item-inner">
          <view class="label-wrap">
            <text>扫码次数限制</text>
          </view>
          <view class="value-wrap flex1 u-text-right">
            <select_tag :active="formData.scan_limit !=0" text="不限制" @select="formData.scan_limit = 0"/>
            <select_tag :active="formData.scan_limit ==0" text="自定义"
                        @select="openModal('scan_limit','设置扫码次数限制','limit')"/>

          </view>
        </view>
        <view class="desc-text">不设置次数限制，默认为不限制次数</view>
        <view class="desc-text" style="margin-top: -30rpx;">过期时间和次数有一个到达限制，则二维码不</view>

      </view>
    </view>
    <view class="form-item" style="padding-bottom: 0;">
      <view class="form-item-inner">
        <view class="label-wrap">
          <text>查看权限</text>
        </view>
        <view class="value-wrap flex1  u-text-right">
          <select_tag :active="formData.password !=''" text="任何人" @select="formData.password = ''"/>
          <select_tag :active="formData.password ==''" text="加密"
                      @select="openModal('password','设置密码','password')"/>

        </view>
      </view>
      <view class="desc-text" style="margin-top: -10rpx;">可设置访问密码</view>
    </view>
    <view class="form-item">
      <view class="form-item-inner">
        <view class="label-wrap">
          <text>表单数据</text>
        </view>
        <view class="value-wrap flex1  u-text-right">
        </view>
      </view>
      <view class="desc-text" style="margin-top: -10rpx;">用户进入二维码之前需要提交的表单</view>
      <view>
        <select_tag :active="!formData.form_data.includes('name')" text="姓名" @select="onSelectFormTag('name')"/>
        <select_tag :active="!formData.form_data.includes('corporate_name')" text="公司名称"
                    @select="onSelectFormTag('corporate_name')"/>
        <select_tag :active="!formData.form_data.includes('mobile')" text="手机号" @select="onSelectFormTag('mobile')"/>
        <select_tag :active="!formData.form_data.includes('id_card')" text="身份证"
                    @select="onSelectFormTag('id_card')"/>

      </view>
    </view>
    <view class="form-item" style="padding-bottom: 0;border-bottom: unset;">
      <view class="form-item-inner">
        <view class="label-wrap">
          <text>表单白名单</text>
        </view>
        <view class="value-wrap flex1  u-text-right">
          <u-switch v-model="formData.is_whitelist"></u-switch>
        </view>
      </view>
      <view class="desc-text" style="margin-top: -10rpx;">用户扫码需输入正确的信息才能提交表单</view>
      <view v-if="formData.is_whitelist && formData.form_data.length > 0" style="padding-bottom: 30rpx;">
        <view class="row row-end" >
          <select_tag :active="0" text="添加"
                      @select="formData.whitelist_verification.push({})"/>
        </view>
        <view class="form-wrap mt30" v-for="(item,index) in formData.whitelist_verification" :key="index">
          <view class="title-area row row-between">
            <view>白名单{{index + 1}}</view>
            <u-icon name="close" color="#e74c3c" @click="formData.whitelist_verification.splice(index,1)"></u-icon>
          </view>
          <view class="form-item" v-if="formData.form_data.includes('name')">
            <view class="form-item-inner">
              <view class="label-wrap">
                <text class="required">*</text>
                <text>姓名</text>
              </view>
              <view class="value-wrap">
                <input class="input" v-model="item.name" placeholder-class="input-pl" placeholder="请输入姓名"/>
              </view>
            </view>
          </view>
          <view class="form-item" v-if="formData.form_data.includes('corporate_name')">
            <view class="form-item-inner">
              <view class="label-wrap">
                <text class="required">*</text>
                <text>公司名称</text>
              </view>
              <view class="value-wrap">
                <input class="input" v-model="item.corporate_name" placeholder-class="input-pl" placeholder="请输入公司名称"/>
              </view>
            </view>
          </view>
          <view class="form-item" v-if="formData.form_data.includes('mobile')">
            <view class="form-item-inner">
              <view class="label-wrap">
                <text class="required">*</text>
                <text>手机号</text>
              </view>
              <view class="value-wrap">
                <input class="input" v-model="item.mobile" placeholder-class="input-pl" placeholder="请输入手机号"/>
              </view>
            </view>
          </view>
          <view class="form-item" v-if="formData.form_data.includes('id_card')">
            <view class="form-item-inner">
              <view class="label-wrap">
                <text class="required">*</text>
                <text>身份证</text>
              </view>
              <view class="value-wrap">
                <input class="input" v-model="item.id_card" placeholder-class="input-pl" placeholder="请输入身份证"/>
              </view>
            </view>
          </view>
        </view>
      </view>

    </view>
    <view class="title-area"></view>


  </view>


  <view class="btn-wrap">
    <u-button :custom-style="{background:'#165DFF',color:'white',marginBottom:'20rpx'}" @click="onSubmit">生成二维码
    </u-button>
  </view>
</view>
</template>

<script>
import {uploadFile} from "../../../utils/tools.js";
import {apiGetCodeDetail, apiGetProductList, apiQrcodeAction} from "../../api/dynamic_code.js";
import select_tag from "./comps/select_tag.vue";

export default {
  components: {
    select_tag
  },
  data() {
    return {
      productList: [],
      modalOption: {
        title: '',
        show: false,
        showCitySelect: false,
        field: '',
        type: 'input',
        value: undefined,
        extra: {}
      },
      formData: {
        // 产品ID 逗号分隔
        goods_ids: [],
        // 二维码名称
        name: '',
        // 备注
        notes: '',
        // 经理姓名
        manager_name: '',
        // 经理手机号
        manager_phone: '',
        //  显示产品logo：0不显示；1显示 （单品才能设置显示）
        is_display_logo: 0,
        //  显示到期时间：0不显示；1显示
        is_display_expiration: 0,
        // 失效时间：0-永久；传分钟数
        end_time: 0,
        // 限制扫码次数：0-不限；
        scan_limit: 0,
        //  密码：不填则为不限；填了必须验证
        password: '',
        //  表单数据：name-姓名；corporate_name-公司名；mobile-手机号；id_card-身份证；（多个之间逗号分隔）
        form_data: [],
        // 白名单校验对象 {key：value}
        whitelist_verification: [],
        //     白名单验证：0-不校验；1-开启白名单
        is_whitelist: 0,
        id: ''
      }
    };
  },
  async onLoad({id}) {
    if(id){
      this.$nextTick(async ()=>{
        let res = await apiGetCodeDetail({id});
        if(res.code == 1){
          let data = res.data;
          this.formData = data;
          let productIds = this.productList.map(p=>p.id);
          this.formData.goods_ids = data.goods_ids.split(',').map(item=>Number(item)).filter((item)=>{
            return  productIds.includes(item);
          })
          this.formData.end_time = data.end_time_m;
        }
      })

    }
  },
  created() {
    this.init();
  },
  methods: {
    async init() {
      const res = await apiGetProductList({page: 1, page_size: 1000, status: 1});
      this.productList = res.data.list;
    },
    async onSubmit() {
      const d = {...this.formData};
      for (const dKey in d) {
        if(dKey === 'whitelist_verification'){
          continue;
        }
        if (Array.isArray(d[dKey])) {
          d[dKey] = d[dKey].join(',');
        }else if (typeof d[dKey] == 'boolean') {
          d[dKey] = String(Number(d[dKey]));
        }
      }
      if(!d.goods_ids){
        uni.$u.toast('请选择产品');
        return;
      }
      if(!d.name){
        uni.$u.toast('请输入二维码名称');
        return;
      }
      if(!d.manager_name){
        uni.$u.toast('请输入客户经理姓名');
        return;
      }

      try {
        uni.showLoading();
        const res = await apiQrcodeAction(d);
        if(res.code == 1){
          if(d.id){
            uni.$u.toast('成功');
          }else{
            uni.navigateTo({
              url:'/yixu/pages/dynamic_code/preview_qrcode?id=' +res.data
            })
          }
        }else{
          uni.$u.toast(res.msg);
        }
      } finally {

      }
    },
    onSelectFormTag(tag, field = 'form_data') {
      let fd = this.formData[field];
      if (fd.includes(tag)) {
        fd.splice(fd.indexOf(tag), 1)
      } else {
        fd.push(tag);
      }
    },
    onModalConfirm() {
      let {field, value} = this.modalOption;
      this.formData[field] = value;
      this.modalOption.show = false;
    },
    openModal(field, title, type, extra = {}) {
      if (type === 'upload') {
        this.selectAvatar();
      } else if (type === 'city') {
        this.modalOption.showCitySelect = true;
      } else {
        this.modalOption.show = true;
      }
      this.modalOption.title = title;
      this.modalOption.type = type;
      this.modalOption.field = field;
      this.modalOption.value = this.formData[field];
      this.modalOption.extra = extra;
    },
    back(){
      uni.navigateBack();
    }
  }
}
</script>

<style lang="scss" scoped>
page {
  background: white;
}

.readonly {
  position: relative;
  z-index: 1;

  &::after {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 2;
  }
}

::v-deep .u-search {
  background: transparent !important;
  padding: 0 !important;

  .u-content {
    padding: 0 30rpx;
  }
}

.input-wrap {
  border: 2rpx solid #efefef;
  padding: 10rpx 30rpx;

  .modal-input {
    border: unset;
    outline: unset;
  }
}


.main-color {
  color: #165DFF;
}

.desc-text {
  color: #666666;
  padding: 20rpx 0;
  font-size: 24rpx;
}

.btn-wrap {
  padding: 30rpx;
  margin-top: 0rpx;
}

::v-deep .u-size-default {
  padding: 12rpx 12rpx;
}

::v-deep .uploader-container .uplader-upload {
  background: #F7F8FA !important;

  .uicon-camera {
    color: #86909C !important;
    position: relative;
    top: -14rpx !important;

    &::after {
      content: '照片';
      position: absolute;
      font-size: 20rpx;
      bottom: -26rpx;
      left: 0;
      right: 0;
      text-align: center;
    }
  }
}

.form-wrap {
  .title-area {
    padding: 18rpx 20rpx;
    margin: 0 10rpx;
    background: #F2F2F2;
    color: #333333;
    font-size: 30rpx;
    font-weight: 500;
    letter-spacing: 2rpx;
  }
}

.back-wrap {
  display: flex;
  align-items: center;
  padding-left: 30rpx;
  gap: 10rpx;

  image {
    width: 30rpx;
    height: 30rpx;
  }

  text {
    font-weight: bold;
  }
}

.form-item {
  background: white;
  padding: 30rpx 30rpx 30rpx 0;
  margin-left: 30rpx;
  margin-top: 5rpx;
  border-bottom: 2rpx solid #f2f2f2;

  &:last-child {
    border-bottom: unset;
  }

  .form-item-inner {
    display: flex;
    align-items: center;
    gap: 30rpx;

  }

  .extra-wrap {
    padding-top: 20rpx;
  }

  .label-wrap {
    color: #1D2129;
    font-size: 30rpx;
    font-weight: 400;
    letter-spacing: 3rpx;
    min-width: 80px;

    .required {
      color: red;
    }
  }

  .value-wrap {
    .input {
      font-size: 30rpx;
      color: #1D2129;
    }

    .input-pl {
      color: #C9CDD4;
    }
  }
}
</style>
